package com.alibaba.datax.plugin.reader.excelreader;

import com.alibaba.datax.common.plugin.RecordSender;
import com.alibaba.datax.common.plugin.TaskPluginCollector;
import com.alibaba.datax.common.util.Configuration;
import com.alibaba.datax.plugin.unstructuredstorage.reader.excelUtil.ExcelReaderUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson2.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;

/**
 * Created by lizhangxue on 24-7-04.
 */
public class ExcelNoModelDataListener extends AnalysisEventListener<Map<Integer, String>> {

    private static final Logger logger = LoggerFactory.getLogger(ExcelReader.Task.class);
    private final String fileName;
    private final Configuration readerSliceConfig;
    private final RecordSender recordSender;
    private final TaskPluginCollector taskPluginCollector;

    public ExcelNoModelDataListener(String fileName, Configuration readerSliceConfig, RecordSender recordSender, TaskPluginCollector taskPluginCollector) {
        this.fileName = fileName;
        this.readerSliceConfig = readerSliceConfig;
        this.recordSender = recordSender;
        this.taskPluginCollector = taskPluginCollector;
    }

    @Override
    public void invoke(Map<Integer, String> data, AnalysisContext context) {
        dealRowsData(data);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        //数据刷新到channel
        logger.info("数据刷新到channel！");
        recordSender.flush();
        logger.info(String.format("所有数据解析完成！文件路径: %s", fileName));
    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        // 处理表头数据
        logger.info(String.format("读取文件路径 %s, 文件表头数据：%s", fileName, headMap));
        // 设置跳过几行后，不再读取表头，以跳过行数优先
        Integer skipRows = this.readerSliceConfig.getInt(com.alibaba.datax.plugin.unstructuredstorage.reader.Key.SKIP_ROWS);
        if (skipRows != null) {
            logger.info(String.format("文件路径为 %s 的文件跳过前 %s 行", fileName, skipRows));
            return;
        }
        Boolean skipHeader = readerSliceConfig.getBool(com.alibaba.datax.plugin.unstructuredstorage.reader.Key.SKIP_HEADER,
                com.alibaba.datax.plugin.unstructuredstorage.reader.Constant.DEFAULT_SKIP_HEADER);
        if (!skipHeader) {
            dealRowsData(headMap);
        } else {
            logger.info(String.format("文件路径为 %s 的文件跳过表头数据", fileName));
        }

    }

    /**
     * 每一行数据处理
     * @param data 行数据
     */
    private void dealRowsData(Map<Integer, String> data) {
        if (data != null) {
            String[] parseRows = data.values().toArray(new String[0]);
            ExcelReaderUtil.readFromStream(parseRows, fileName, readerSliceConfig, recordSender, taskPluginCollector);
        }
    }

}
